package com.woniu.smallmedical.configuration;


import com.woniu.smallmedical.realm.ShiroRealm;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author author
 * @create 2021-09-26-9:00
 */
@Configuration
public class ShiroConfiguration {
    //强制开启内存缓存管理
    @Bean
    public MemoryConstrainedCacheManager memoryConstrainedCacheManager(){
        return new MemoryConstrainedCacheManager();
    }
    //将ShiroRealm注入sping容器
    @Bean
    public ShiroRealm shiroRealm(MemoryConstrainedCacheManager memoryConstrainedCacheManager){

        ShiroRealm shiroRealm=new ShiroRealm();

        shiroRealm.setCacheManager(memoryConstrainedCacheManager);
        return shiroRealm;

    }

    /**
     * 将DefaultWebSecurityManager注入到Spring容器
     * @param shiroRealm 在容器中查找ShiroRealm对象参数
     * @return
     */
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(ShiroRealm shiroRealm){
        //创建安全管理器
        DefaultWebSecurityManager defaultWebSecurityManager=new DefaultWebSecurityManager();
        //设置Realm域
        defaultWebSecurityManager.setRealm(shiroRealm);
        //返回安全管理器
        return defaultWebSecurityManager;
    }

    /**
     * Shiro认证授权过滤工厂
     * @param defaultWebSecurityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        //创建Shiro过滤工厂
        ShiroFilterFactoryBean shiroFilterFactoryBean=new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        Map<String,String> filterMap=new LinkedHashMap<String,String>();
        filterMap.put("/login", "anon");
        filterMap.put("/logout", "logout");
        filterMap.put("/**", "authc");
        shiroFilterFactoryBean.setLoginUrl("/login.html");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        return shiroFilterFactoryBean;
    }
}
